package com.app.coderead;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.logging.Logger;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.*;

@SuppressWarnings("serial")
public class CodereadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        processRequest(req, resp);
    } 

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        processRequest(req, resp);
    }
    
    public void processRequest(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String TAG = this.getClass().getName();
        Logger log = Logger.getLogger(TAG);
        
        
        String docName = req.getParameter("doc");
        
        
        File file = new File("WEB-INF/doc/" + docName);
        //將檔案存為串流
        InputStream in = new FileInputStream(file);
        
        //串流依據encoding 編碼 並使用buffer
        Reader reader = new InputStreamReader(in, "UTF-8");
        reader = new BufferedReader(reader);
        
        StringBuffer sb = new StringBuffer();
        int c;
        while((c = reader.read()) != -1) {
            sb.append((char)c);
        }
        reader.close();
//        log.info("file.isFile() : " + file.isFile());
//        req.setAttribute("doc", file.isFile());
        req.setAttribute("doc", sb);
        RequestDispatcher view = req.getRequestDispatcher("/page/output.jsp");
        view.forward(req, resp);
        
//        resp.getWriter().println("file.isFile() : " + file.isFile());
    }
}
